#!/usr/bin/env ruby
require File.dirname(__FILE__) + '/lib/roker'
require 'ruby-debug'

args = ARGV.join(' ')

help = !(args =~ /--help/).nil?

if help
  puts "Roker provides weather forecasts from weather.gov."
  puts "\tUsage: roker [options...]\n"
  puts "\tOptions:"
  puts "\t\t--date DATE\t\t\tForecast date (mm/dd/yyyy)"
  puts "\t\t--lat LATITUDE\t\t\tForecast latitude (37.0625)"
  puts "\t\t--lng LONGITUDE\t\t\tForecast longitude (-95.677)"
  puts "\t\t--xml\t\t\t\tDisplay xml result from weather.gov"
  puts "\t\t--help\t\t\t\tDisplay this help message"
  exit
end

if args =~ /--date *(\d+\/\d+\/\d+)/
  $1 =~ /(\d+)\/(\d+)\/(\d+)/
  started_at = Time.mktime($3.to_i, $1.to_i, $2.to_i, 0, 0, 0, 0, 0).beginning_of_day
end

lat = $1.to_f if args =~ /--lat *([0-9\.\-\+]+)/
lng = $1.to_f if args =~ /--lng *([0-9\.\-\+]+)/

xml = !(args =~ /--xml/).nil?

started_at  ||= Time.now.beginning_of_day + 1.day
ended_at    ||= started_at.end_of_day
lat         ||= 37.0625
lng         ||= -95.677068

puts "Roker says the forecast for #{started_at.strftime("%B %d, %Y")} in #{lat}, #{lng} is:\n"

roker = Roker.new(:started_at => started_at, :ended_at => ended_at, :lat => lat, :lng => lng)

forecast_str = ''

roker.weather_forecasts_attributes.each do |wfa|
  # wfa => {
  #   :started_at                   => Sat Dec 05 00:17:32 -0500 2009, 
  #   :ended_at                     => Sat Dec 05 03:17:32 -0500 2009,
  #   :lat                          => 37.0625,
  #   :lng                          => -95.677068,
  #   :wind_speed                   => 7.0, 
  #   :minimum_temperature          => 21.0, 
  #   :wind_direction               => 180.0, 
  #   :temperature                  => 24.0, 
  #   :cloud_cover                  => 0.0, 
  #   :dewpoint_temperature         => 12.0, 
  #   :relative_humidity            => 60.0, 
  #   :liquid_precipitation         => 0.0, 
  #   :maximum_temperature          => nil, 
  #   :wave_height                  => 0.0, 
  #   :probability_of_precipitation => 0.0
  # }
  temp  = (wfa[:temperature].nil? || wfa[:temperature].nan?) ? '?' : wfa[:temperature].to_i.to_s
  pop   = (wfa[:probability_of_precipitation].nil? || wfa[:probability_of_precipitation].nan?) ? '?' : wfa[:probability_of_precipitation].to_i.to_s
  forecast_str << wfa[:started_at].strftime("%I:%M%p") + "\t" + temp + " deg" + "\t" + pop + "% P.O.P."
  forecast_str << "\n"
end

puts forecast_str

if xml
  puts "XML:\n"
  puts roker.weather_xml
end